package github.ziwukun.jsonql.orm;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import github.ziwukun.jsonql.utils.RefUtils;

/**
 * 类型装换器<br>
 * @author Hugo.Yu
 */
public interface PropConverter<T> {
	public static class ContainerFieldConverterContainer{
		private static Map<Class<? extends PropConverter<?>>,Object> converters = new ConcurrentHashMap<>();
	}
	/**
	 * 获取实现类的对象，缓存
	 * @param clazz
	 * @return
	 */
	public static PropConverter<?> getConverter(
		Class<? extends PropConverter<?>> clazz) {
		
		if(!ContainerFieldConverterContainer.converters.containsKey(clazz)) {
			synchronized (PropConverter.class) {
				if(!ContainerFieldConverterContainer.converters.containsKey(clazz)) {
					ContainerFieldConverterContainer.converters
						.put(clazz, RefUtils.newInstance(clazz));
				}
			}
		}
		
		return (PropConverter<?>) ContainerFieldConverterContainer
			.converters.get(clazz);
	}
	
	/**
	 * 直接转换
	 * @param sourceObj
	 * @param targetClazz
	 * @return
	 */
	public static Object convert(Object originValue,Class<? extends PropConverter<?>> targetClazz) {
		if(originValue == null) {
			return null;
		}
		
		return getConverter(targetClazz).convert(originValue);
	}
	/**
	 * 转换字段类型
	 * @param originValue
	 * @return
	 */
	T convert(Object originValue);
}